<?php

namespace App\Common\Util\Response;

use App\Common\Util\AdminAuth;
use App\Common\Util\TP;
use Sc\Util\HtmlStructure\Html\Html;
use think\facade\App;

/**
 * Class View
 */
class View
{
    const TEMPLATE_SUFFIX = '.sc.php';

    public function __construct(protected readonly string $template,
                                protected array $vars
    ){}


    public function render(): string
    {
        if ($filename = $this->getScPath($this->template)) {
            return $this->scRender($filename);
        }

        return \think\facade\View::fetch($this->getViewPath($this->template), $this->thinkViewVar());
    }

    private function thinkViewVar(): array
    {
        $this->vars['TP'] = [];

        return $this->vars;
    }

    public function getViewPath(string $path): array|string|null
    {
        if (str_starts_with($path, 'plugins')) {
            $appName = \app('http')->getName();

            return preg_replace('/^(plugins\/\w+\/)(.*)/', "../$1/$appName/View/$2.php", $path);
        }

        return $path;
    }


    private function getScPath(string $template): ?string
    {
        $appName = \app('http')->getName();
        if (str_starts_with($template, 'plugins')) {
            if (!preg_match('/^plugins\/(\w+)\/(.+)/', $template, $match)) {
                return null;
            }
            $template   = "plugins/{$match[1]}/{$appName}/View/$match[2]";
            $scPath = implode('/', [App::getRootPath(), $template]);
        }else{
            $scPath = implode('/', [App::getAppPath(), 'View', $template]);
        }

        $filename = $scPath . self::TEMPLATE_SUFFIX;

        if (file_exists($filename)) {
            return $filename;
        }

        return null;
    }

    /**
     * @param string $filename
     *
     * @return string
     */
    private function scRender(string $filename): string
    {
        extract($this->vars);

        $body = include realpath($filename);
        if (!Html::html()) {
            Html::create("新页面");
        }

        Html::html()->find('#app')->append($body);

        if (Html::theme() === 'ElementUI') {
            Html::js()->vue->set('is_super', AdminAuth::isSuper());
        }
        return \think\facade\View::display(Html::toHtml());
    }
}